package com.sjyp.cms.commons.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.sjyp.cms.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class AdminInterceptor implements Interceptor{
    private final static Logger logger = LoggerFactory.getLogger(AdminInterceptor.class);
    private static Map menuMap;
    static{
        menuMap = new HashMap();
        menuMap.put("/admin", 1);
        menuMap.put("/admin/column", 2);
        menuMap.put("/admin/picture", 3);
        menuMap.put("/admin/article", 4);
        menuMap.put("/admin/user", 5);
    }

    @Override
    public void intercept(Invocation ai) {
        //1、验证权限 getControllerKey 不包含方法  getActionKey包含方法
        String actionKey = ai.getActionKey();
        Controller controller = ai.getController();
        if (!("/admin".equals(actionKey)) && !("/admin/home".equals(actionKey))) {
            User user = controller.getSessionAttr("loginUser");
            if (null == user) {
                controller.render("login.html");
                return;
            }
        }
        //2、处理异常
        try {
            ai.invoke();
        } catch (Exception e) {
            logger.error("请求异常",e);
            controller.render("500.html");
            return ;
        }
        //2、根据请求Key激活当前菜单为选中
        ai.getController().setAttr("currentMenu",menuMap.get(ai.getControllerKey()));
    }
}
